package com.vehiclemanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vehiclemanagement.entity.FuelCard;
import com.vehiclemanagement.mapper.FuelCardMapper;
import com.vehiclemanagement.service.FuelCardService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 加油卡服务实现类
 */
@Service
public class FuelCardServiceImpl extends ServiceImpl<FuelCardMapper, FuelCard> implements FuelCardService {

    @Autowired
    private FuelCardMapper fuelCardMapper;

    @Override
    public IPage<FuelCard> pageFuelCards(Integer current, Integer size, String searchTerm, String status, Boolean includeDeleted) {
        // 创建分页对象
        Page<FuelCard> page = new Page<>(current, size);
        
        // 创建自定义SQL条件
        String whereSql = " 1=1 ";
        
        // 添加搜索条件 - 支持多字段搜索
        if (StringUtils.isNotBlank(searchTerm)) {
            whereSql += " AND (card_number LIKE '%" + searchTerm + "%' OR type LIKE '%" + searchTerm + "%' OR remark LIKE '%" + searchTerm + "%') ";
        }
        
        // 添加状态查询条件
        if (StringUtils.isNotBlank(status)) {
            whereSql += " AND status = '" + status + "' ";
        }
        
        // 处理删除标志 - 由于现在使用物理删除，这部分逻辑保留但实际没有已删除记录
        if (Boolean.TRUE.equals(includeDeleted)) {
            // 查询已删除的加油卡 - 实际上物理删除后无法查询到
            System.out.println("查询已删除的加油卡");
            whereSql += " AND del_flag = 1 ";
        } else {
            // 默认查询未删除的加油卡
            System.out.println("只查询未删除的加油卡");
            whereSql += " AND del_flag = 0 ";
        }
        
        // 添加排序
        whereSql += " ORDER BY create_time DESC";
        
        System.out.println("执行查询SQL条件: " + whereSql);
        
        // 执行查询
        return fuelCardMapper.selectPageWithDeleted(page, whereSql);
    }

    @Override
    public FuelCard getFuelCardById(Long id) {
        return fuelCardMapper.selectById(id);
    }

    @Override
    public boolean existsActiveCardWithNumber(String cardNumber) {
        return fuelCardMapper.existsActiveCardWithNumber(cardNumber) > 0;
    }

    @Override
    public boolean addFuelCard(FuelCard fuelCard) {
        System.out.println("服务层开始添加加油卡: " + fuelCard);
        
        try {
            // 检查卡号是否已存在
            LambdaQueryWrapper<FuelCard> query = new LambdaQueryWrapper<>();
            query.eq(FuelCard::getCardNumber, fuelCard.getCardNumber());
            Long count = fuelCardMapper.selectCount(query);
            
            // 如果存在相同卡号，则添加失败
            if (count != null && count > 0) {
                System.out.println("添加加油卡失败：卡号已存在 - " + fuelCard.getCardNumber());
                return false;
            }
            
            // 设置默认值
            if (fuelCard.getCreateTime() == null) {
                fuelCard.setCreateTime(LocalDateTime.now());
            }
            if (fuelCard.getUpdateTime() == null) {
                fuelCard.setUpdateTime(LocalDateTime.now());
            }
            if (fuelCard.getDelFlag() == null) {
                fuelCard.setDelFlag(0);
            }
            if (fuelCard.getBalance() == null) {
                fuelCard.setBalance(BigDecimal.ZERO);
            }
            
            // 执行插入
            System.out.println("准备插入新记录: " + fuelCard);
            int result = fuelCardMapper.insert(fuelCard);
            System.out.println("插入结果: " + result + ", 生成的ID: " + fuelCard.getId());
            
            return result > 0;
        } catch (Exception e) {
            System.err.println("添加加油卡发生异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateFuelCard(FuelCard fuelCard) {
        // 更新时间
        fuelCard.setUpdateTime(LocalDateTime.now());
        
        return fuelCardMapper.updateById(fuelCard) > 0;
    }

    @Override
    public boolean deleteFuelCard(Long id) {
        // 使用物理删除而不是逻辑删除
        System.out.println("执行物理删除加油卡，ID: " + id);
        
        try {
            // 先查询出卡信息，方便记录日志
            FuelCard card = fuelCardMapper.selectById(id);
            if (card != null) {
                System.out.println("准备物理删除卡号为 " + card.getCardNumber() + " 的加油卡");
                
                // 直接物理删除记录
                int result = fuelCardMapper.deletePhysically(id);
                System.out.println("物理删除结果: " + result);
                return result > 0;
            } else {
                System.out.println("未找到ID为 " + id + " 的加油卡，无法删除");
                return false;
            }
        } catch (Exception e) {
            System.err.println("删除加油卡时出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<String> getCardTypes() {
        // 查询所有加油卡，然后提取不重复的类型
        LambdaQueryWrapper<FuelCard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(FuelCard::getType);
        queryWrapper.groupBy(FuelCard::getType);
        
        List<FuelCard> fuelCards = fuelCardMapper.selectList(queryWrapper);
        return fuelCards.stream()
                .map(FuelCard::getType)
                .filter(StringUtils::isNotBlank)
                .distinct()
                .collect(Collectors.toList());
    }
} 